import urllib
import hashlib
from xml.dom.minidom import parseString
from django.conf import settings

if not settings.GAE_CACHE_SECRET_KEY:
    raise Exception('GAE_CACHE_SECRET_KEY not set properly! See http://code.google.com/p/django-gae-cache/')

if not settings.GAE_CACHE_URL:
    raise Exception('GAE_CACHE_URL not set properly! See http://code.google.com/p/django-gae-cache/')

class Api:
    def Invalidate(self, path):
        hash = hashlib.sha1(''.join([settings.GAE_CACHE_SECRET_KEY, path])).hexdigest()
        
        url = '%s/_sys/invalidate/%s%s' % (settings.GAE_CACHE_URL, hash, path)
        res = urllib.urlopen(url)
        xml = res.read()

        doc = parseString(xml)
        message = doc.getElementsByTagName('message')[0].firstChild.nodeValue
        status = int(doc.getElementsByTagName('status')[0].firstChild.nodeValue)
        return (status, message)
        
    def InvalidateAll(self):
        hash = hashlib.sha1(settings.GAE_CACHE_SECRET_KEY).hexdigest()
        
        url = '%s/_sys/invalidate-all/%s' % (settings.GAE_CACHE_URL, hash)
        res = urllib.urlopen(url)
        xml = res.read()

        doc = parseString(xml)
        message = doc.getElementsByTagName('message')[0].firstChild.nodeValue
        status = int(doc.getElementsByTagName('status')[0].firstChild.nodeValue)
        return (status, message)

    def Stats(self):
        hash = hashlib.sha1(settings.GAE_CACHE_SECRET_KEY).hexdigest()
        
        url = '%s/_sys/stats/%s' % (settings.GAE_CACHE_URL, hash)
        res = urllib.urlopen(url)
        xml = res.read()
        doc = parseString(xml)
        
        message = doc.getElementsByTagName('message')[0].firstChild.nodeValue
        status = int(doc.getElementsByTagName('status')[0].firstChild.nodeValue)
        lines = doc.getElementsByTagName('data')[0].childNodes
        
        data = {}
        for line in lines:
            if line.nodeType != 1: continue
            data[str(line.nodeName)] = str(line.firstChild.nodeValue)
        
        return (status, message, data)

if __name__ == '__main__':
    api = Api()
    print api.InvalidateAll()
